package com.tool4j.util;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.ExpiryPolicy;

import java.time.Duration;
import java.util.function.Supplier;

/**
 * @author Deng.Weiping
 * @since 2024/9/11 10:16
 */
public class CacheUtil {

    private static final String EN_CACHE_INSTANCE = "encacheInstance";
    // 定义过期策略
    private static final ExpiryPolicy<String, String> expiryPolicy = new ExpiryPolicy<>() {
        @Override
        public Duration getExpiryForCreation(String s, String s2) {
            return Duration.ofMinutes(5); // 5分钟过期
        }

        @Override
        public Duration getExpiryForAccess(String s, Supplier<? extends String> supplier) {
            return null;
        }

        @Override
        public Duration getExpiryForUpdate(String s, Supplier<? extends String> supplier, String s2) {
            return null;
        }
    };

    // 声明一个cacheBuilder
    private static final CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
            .withCache(EN_CACHE_INSTANCE, CacheConfigurationBuilder
                    //声明一个容量为100的堆内缓存
                    .newCacheConfigurationBuilder(String.class, String.class, ResourcePoolsBuilder.heap(100))
                    .withExpiry(expiryPolicy)
            )
            .build(true);

    public static void setCache(String key, String value) {
        // 获取Cache实例
        Cache<String, String> myCache = cacheManager.getCache(EN_CACHE_INSTANCE, String.class, String.class);
        // 写缓存
        myCache.put(key, value);

    }

    public static String getCache(String key) {
        // 获取Cache实例
        Cache<String, String> myCache = cacheManager.getCache(EN_CACHE_INSTANCE, String.class, String.class);
        // 读缓存
        return myCache.get(key);
    }

    public static void removeCache(String key) {
        // 移除
        cacheManager.removeCache(key);
    }

}
